<?php

/**
 * Class Dball
 */
class Dball extends CI_Model
{

    /**
     * @var 用户ID
     */
    private $userid;

    /**
     * Dball constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->sessioninfo = $this->session->userdata('sessioninfo');
        $this->userid = $this->sessioninfo['userId'];
    }
  

    /**
     * 从数据字典表获取需要的信息
     * @return array $result
     */
    public function getDictData($typename = "", $name = "")
    {
        if ($typename == "") {
            $sqlStr = "SELECT * FROM sys_dictdata WHERE type='字典类型' ORDER BY seq";
        } else {
            if ($name == "") {
                $sqlStr = "SELECT * FROM sys_dictdata WHERE type='" . $typename . "' ORDER BY seq";
            } else {
                $sqlStr = "SELECT * FROM sys_dictdata WHERE type='" . $typename . "' and name='" . $name . "'";
            }
        }
        $query = $this->db->query($sqlStr);
        return $query->result_array();
    }

    /**
     * 从配置字典表获取需要的信息
     * @return array $result
     */
    public function getConfData($typename = "", $name = "")
    {
        if ($typename == "") {
            $sqlStr = "SELECT type FROM sys_configdata WHERE group by type";
        } else {
            if ($name == "") {
                $sqlStr = "SELECT * FROM sys_configdata WHERE type='" . $typename . "' ORDER BY seq";
            } else {
                $sqlStr = "SELECT * FROM sys_configdata WHERE type='" . $typename . "' and name='" . $name . "'";
            }
        }
        $query = $this->db->query($sqlStr);
        return $query->result_array();
    }

    /**
     * 获取编号
     * @param string $type 编号的固定开始文字
     * @param integer $num 编号的最加流水号长度,默认2位
     * @return array $result
     */
    public function getNo($type, $num = 2)
    {
        $CI =& get_instance();
        $switch = true;
        while ($switch) {
            $sql = "SELECT * FROM sys_configdata WHERE type='编号生成' AND name = '" . $type . "'";
            $query = $this->db->query($sql);
            $result = $query->result_array();
            if (sizeof($result) == 0) {
                $result = $type . str_pad('1', $num, '0', STR_PAD_LEFT);
                $CI->load->helper('guid_helper');
                $data['id'] = guid();
                $data['type'] = '编号生成';
                $data['seqno'] = $type;
                $data['value'] = '1';
                $data['name'] = $type;
                $data["createdatetime"] = date('Y-m-d G:i:s');
                $data["createuser"] = $this->userid;
                $this->db->insert('sys_configdata', $data);
            } else {
                $no = $result[0]['value'] + 1;
                $data['value'] = $no;
                $data["modifydatetime"] = date('Y-m-d G:i:s');
                $data["modifyuser"] = $this->userid;
                $this->db->where('id', $result[0]['id']);
                $this->db->update('sys_configdata', $data);
                $result = $type . str_pad($no, $num, '0', STR_PAD_LEFT);
            }
            $insert = array();
            $insert['ID'] = $result;
            $switch = !$this->db->insert('sys_key', $insert);
        }
        return $result;
    }

    /**
     * 获取某个UUID,对应表的对应字段
     * @param string $uuid 表的UUID
     * @param string $targettable 表名 默认为oa_project
     * @param string $getField 表字段 默认为projectno
     * @return array $result
     */
    public function getField($uuid, $targettable = 'oa_project', $getField = 'projectno')
    {
        $sql = "SELECT $getField FROM $targettable WHERE uuid='" . $uuid . "'";
        $query = $this->db->query($sql);
        $result = $query->row_array();
        return $result;
    }


    /**
     * 从基础数据表获取需要的信息
     * @param string $table 目的表
     * @param string $disp 查询结果列
     * @param string $where 附加条件
     * @return array $result
     */
    public function getbasedata($table, $disp = "*", $where = "", $deletemode = "UPDATE")
    {
        if ($deletemode == 'UPDATE') {
            $sqlStr = "SELECT $disp FROM $table WHERE (`IS_DISABLED` =0) ";
        } else {
            $sqlStr = "SELECT $disp FROM $table WHERE (0=0) ";
        }
        if (strlen($where) > 0)
            $sqlStr .= " AND (" . $where . ")";
        $query = $this->db->query($sqlStr);
        return $query->result_array();
    }

    /**
     * 从基础数据表获取需要的信息，根据特殊链接
     * @param string $db 数据库链接对象
     * @param string $table 目的表
     * @param string $disp 查询结果列
     * @param string $where 附加条件
     * @return array $result
     */
    public function getbasedatawithdb($db,$table, $disp = "*", $where = "", $deletemode = "UPDATE")
    {
        if ($deletemode == 'UPDATE') {
            $sqlStr = "SELECT $disp FROM $table WHERE (`IS_DISABLED` =0) ";
        } else {
            $sqlStr = "SELECT $disp FROM $table WHERE (0=0) ";
        }
        if (strlen($where) > 0)
            $sqlStr .= " AND (" . $where . ")";
        $query = $db->query($sqlStr);
        return $query->result_array();
    }

    /**
     * 从基础数据表获取字段唯一性值
     * @param string $table 目的表
     * @param string $disp 查询结果列
     * @param string $where 附加条件
     * @return array $result
     */
    public function getgroupdata($table, $field = "name", $where = "", $deletemode = "UPDATE")
    {
        if ($deletemode == 'UPDATE') {
            $sqlStr = "SELECT DISTINCT $field FROM $table WHERE (`IS_DISABLED` =0) ";
        } else {
            $sqlStr = "SELECT DISTINCT $field FROM $table WHERE (0=0) ";
        }
        if (strlen($where) > 0)
            $sqlStr .= " AND (" . $where . ")";
        $query = $this->db->query($sqlStr);
        return $query->result_array();
    }


    /** 获得图片文件列表
     * @param $path 文件路径
     * @param string $suffix 输出文件路径前缀
     * @return array 文件列表
     */
    public function getDirList($path, $suffix = "app/32/")
    {
        $this->load->model("public/Common_tools", "tools");
        $filelist = $this->tools->dir_list(FCPATH . $path);
        $path = base_url() . $path;
        $icons = array();
        foreach ($filelist as $key => $item) {
            $icon = array();
            if (basename($item, ".png") == "Thumbs.db") continue;
            $icon['name'] = basename($item);
            $icon['id'] = $suffix . basename($item);
            $icon['img'] = $path . $icon['name'];
            $icons[] = $icon;
        }
        return $icons;
    }

    /**
     * 从user_define表中提取搜索个人定义
     * @param $type 模块名
     * @param $menudefine 菜单定义
     * @return mixed
     */
    public function processSearchDefine($type, $menudefine)
    {
        $this->db->where("userId", $this->userid);
        $this->db->where('type', $type);
        $define = $this->db->get("user_define")->result_array();
        if (sizeof($define) == 0) return $menudefine;
        $define = $define[0];
        if (!isset($define['searchdefine'])) return $menudefine;
        if ($define['searchdefine'] == "") return $menudefine;
        $menudefine['searchdefine']['items'] = array();
        $searchdefine = json_decode($define['searchdefine'], true);
        $menudefine['searchdefine']['init']['columns'] = ceil(sizeof($searchdefine) / 3);
        $row = 0;
        foreach ($searchdefine as $item) {
            $row++;
            if (!isset($menudefine['initsearchdefine'][$item])) continue;
            $rr = $menudefine['initsearchdefine'][$item];
            $rr['column'] = ceil($row / 3) - 1;
            $menudefine['searchdefine']['items'][] = $rr;
        }
        return $menudefine;
    }

    /** 从user_define表中提取列表个人定义
     * @param $type 模块名
     * @param $griddefine 列表字段定义
     * @return mixed
     */
    public function processListdataDefine($type, $griddefine)
    {
        $this->db->where("userId", $this->userid);
        $this->db->where('type', $type);
        $define = $this->db->get("user_define")->result_array();
        if (sizeof($define) == 0) return $griddefine;
        $define = $define[0];
        if (!isset($define['listdefine'])) return $griddefine;
        if ($define['listdefine'] == "") return $griddefine;
        $griddefine['listfield'] = array();
        $listdatadefine = json_decode($define['listdefine'], true);
        foreach ($listdatadefine as $item) {
            $rr = $griddefine['initlistfield'][$item];
            $griddefine['listfield'][] = $rr;
        }
        return $griddefine;
    }

    /** 保存个人配置，没有新增
     * @param $type 模块名
     * @param $field 保存字段
     * @param $define 保存的字段信息
     */
    public function saveDefine($type, $field, $define)
    {
        $this->db->where("userId", $this->userid);
        $this->db->where('type', $type);
        $data = $this->db->get('user_define')->result_array();
        if (sizeof($data) == 0) {
            $insert = array();
            $insert['userId'] = $this->userid;
            $insert['type'] = $type;
            $insert[$field] = $define;
            $insert['IS_DISABLED'] = 0;
            $insert['createdatetime'] = Date('Y-m-d H:i:s');
            $insert['createuser'] = $this->userid;
            $this->db->insert('user_define', $insert);
        } else {
            $this->db->where("ID", $data[0]['ID']);
            $update = array();
            $update[$field] = $define;
            $update['modifydatetime'] = Date('Y-m-d H:i:s');
            $update['modifyuser'] = $this->userid;
            $this->db->update('user_define', $update);
        }
    }


    /**  对记录在表中某个字段的唯一性进行校验
     *
     * @param $type create/edit
     * @param $result _beforeDBAct中的对象
     * @param $config {"id":"id","field":"name","table":"sys_user"}
     * @param $where STATUS='正常'
     */
    public function dbUniqueCheck($type, $result, $config, $where = "")
    {
        if ($type == 'create') {
            if ($where <> "") $this->db->where($where);
            $this->db->where($config["field"], $result[$config["field"]]);
            $data = $this->db->get($config["table"])->result_array();
            if (sizeof($data) > 0) {
                $this->_JSONRESULT("唯一性约束条件不满足！");
            }
        } else {
            if ($where <> "") $this->db->where($where);
            $this->db->where_not_in($config["id"], $result[$config["id"]]);
            $this->db->where($config["field"], $result[$config["field"]]);
            $data = $this->db->get($config["table"])->result_array();
            if (sizeof($data) > 0) {
                $this->_JSONRESULT("唯一性约束条件不满足！");
            }
        }
    }

    /** 根据表名，取得数据字段，排除默认字段
     * @param $table
     * @return array
     */
    public function getFieldDefine($table)
    {
        $fields = $this->db->list_fields($table);
        unset($fields[0]);
        $result = array();
        if (in_array("IS_DISABLED", $fields)) {
            foreach ($fields as $item) {
                if (!in_array($item, array("IS_DISABLED", "createdatetime", "createuser", "modifydatetime", "modifyuser"))) {
                    $result[] = $item;
                }
            }
        }
        return $result;
    }

    /** AJAX 返回 跟踪信息,直接返回了
     * @param string $message
     * @param bool $ok
     */
    protected function _JSONRESULT($message = '错误信息', $ok = false)
    {
        $result = array();
        $result["success"] = $ok;
        $result["msg"] = print_r($message, true);
        $result["obj"] = "";
        echo json_encode($result);
        exit;
    }

    public function logAction($type, $table, $data, $key = "ID")
    {
        if (isset($data[$key]))
            $str = "记录编号【" . $data[$key] . "】,";
        else $str = "";
        if ($type == "create") {
            $str .= "新增记录,";
            foreach ($data as $key => $item) {
                $str .= "字段【" . $key . "】=【" . $item . "】,";
            }
        }
        if ($type == "delete") {
            $str .= "删除记录,";
        }
        $insert = array();
        $insert['name'] = '编辑处理';
        $insert['table'] = $table;
        $insert['desc'] = $str;
        $insert['logTime'] = Date('Y-m-d H:i:s');
        $insert['operator'] = $this->sessioninfo['fullName'];
        $this->db->insert("sys_log", $insert);
    }
}
